/**
 * 获取缺陷列表
 *
 * Created by nongzhizhong on 2022/08/11.
 */
const chai = require('chai');
chai.use(require('chai-http'));
const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const benchmark = require('./../../../benchmark/static-analyze/gjb.json');
const defects = require('./../../../../phoenix/models/defects');

module.exports = describe('/GET /project-versions/:projectVersionId/defects.json', function () {
  const administrator = new Administrator();
  let project = {};
  let projectVersion = {};
  let newUser;

  function url(versionId) {
    return `/project-versions/${versionId}/defects.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUser = tester;
        return newUser.createRandomProject('c++');
      })
      .then((res) => {
        project = res;
        return project.createStaticAnalyzeVersion(
          benchmark.verified_rules,
          benchmark.files,
          newUser
        );
      })
      .then((res) => {
        projectVersion = res;
        return projectVersion.rootDirectory.staticAnalyze();
      })
      .then(() => projectVersion.project.creator.waiting4TasksOfVersionFinished(
        projectVersion.versionId
      ))
      .then(done)
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers([newUser.userId])
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'get');
  common.should.be.tester(uri, url, 'get');

  // 根据文件Id过滤缺陷
  Object.keys(benchmark.result.defectsListFilterByFile).forEach((fileName) => {
    it(`it should get defects list filter by file ${fileName} successfully`, function (done) {
      projectVersion.rootDirectory.getTree()
        .then((fileTree) => {
          let fileId;
          fileTree.tree.children.forEach((child) => {
            if (child.fileName !== fileName) {
              return;
            }
            fileId = child.id;
          });
          return fileId;
        })
        .then((fileId) => {
          chai.request(uri)
            .get(url(projectVersion.versionId))
            .query({ fileId })
            .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
            .end((err, res) => {
              res.should.have.status(200);
              common.should.be.equal.defectsList(
                res.body,
                benchmark.result.defectsListFilterByFile[fileName],
                'defectsList|ruleCode'
              );
              done();
            });
        })
        .catch(done);
    });
  });

  // 根据规范Id过滤缺陷
  Object.keys(benchmark.result.defectsListFilterByRule).forEach((ruleCode) => {
    it(`it should get defects list filter by rule ${ruleCode} successfully`, function (done) {
      new Promise((resolve, reject) => {
        chai.request(uri)
          .get(url(projectVersion.versionId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            if (err) {
              reject();
            }
            res.body.defectsList.forEach((defect) => {
              if (defect.ruleCode === ruleCode) {
                resolve(defect.ruleId);
              }
            });
          });
      })
        .then((ruleId) => {
          chai.request(uri)
            .get(url(projectVersion.versionId))
            .query({ ruleId })
            .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
            .end((err, res) => {
              res.should.have.status(200);
              common.should.be.equal.defectsList(
                res.body,
                benchmark.result.defectsListFilterByRule[ruleCode],
                'defectsList|fileName|ruleCode'
              );
              done();
            });
        })
        .catch(done);
    });
  });

  // 根据规范级别过滤缺陷
  Object.keys(benchmark.result.defectsListFilterByLevel).forEach((levels) => {
    it(`it should get defects list filter by levels ${levels} successfully`, function (done) {
      chai.request(uri)
        .get(url(projectVersion.versionId))
        .query({ level: levels.split(',') })
        .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
        .end((err, res) => {
          res.should.have.status(200);
          common.should.be.equal.defectsList(
            res.body,
            benchmark.result.defectsListFilterByLevel[levels],
            'fileName|ruleCode|locations.begin.line|locations.end.column'
          );
          done();
        });
    });
  });

  // 根据缺陷状态过滤缺陷
  it('it should get defects list filter by status successfully', function (done) {
    const status = defects.defectStatus.ignore;
    new Promise((resolve, reject) => {
      chai.request(uri)
        .get(url(projectVersion.versionId))
        .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
        .end((err, res) => {
          if (err) {
            reject();
          }
          resolve(res.body.defectsList[0].defectId.toString());
        });
    })
      .then((defectId) => new Promise((resolve, reject) => {
        chai.request(uri)
          .put(`/project-versions/${projectVersion.versionId}/defects/update.json`)
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .send({ status, defectIds: [defectId] })
          .end((err, res) => {
            if (err) {
              reject();
            }
            res.should.have.status(204);
            resolve(defectId);
          });
      }))
      .then((defectId) => {
        chai.request(uri)
          .get(url(projectVersion.versionId))
          .query({ status })
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            res.body.defectsList.should.have.length(1);
            res.body.defectsList[0].should.have.property('defectId');
            res.body.defectsList[0].defectId.should.equal(defectId);
            done();
          });
      })
      .catch(done);
  });
});
